const { getAccountInfoByUsername } = require('../model/account');
const message = require('../model/returnMessage');
const md5 = require('../utils/md5');
const jwt = require('../utils/jwt');
const { jwtSecret } = require('../config/config.default');

module.exports.login = async (req, res, next) => {
  getAccountInfoByUsername(req.body.username).then(
    (r) => {
      if (md5(req.body.password) === r[0].password) {
        jwt
          .sign({ username: req.body.username }, jwtSecret, {
            expiresIn: '24h',
          })
          .then(
            (_r) => {
              res
                .status(200)
                .json(
                  message(
                    { username: r[0].username, token: _r },
                    'Login success.'
                  )
                );
            },
            (_e) => {
              res.status(500).json(message({}, 'Internal server error.'));
            }
          );
      } else {
        res.status(401).json(message({}, 'Password error.'));
      }
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error.'));
    }
  );
};
